package com.paw.core.intercepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.paw.common.constant.CommonConstant;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author Rubble
 * @date 2021/9/3
 **/
public class TraceInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String traceId = request.getHeader(CommonConstant.TRACE_ID);
    String permId = request.getHeader(CommonConstant.PERM_ID);
    String requestId = request.getHeader(CommonConstant.REQUEST_ID);
    MDC.put(CommonConstant.TRACE_ID,traceId);
    MDC.put(CommonConstant.PERM_ID,permId);
    MDC.put(CommonConstant.REQUEST_ID,requestId);
    return true;
  }

  @Override
  public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    MDC.clear();
  }
}
